<template>
  <div>

    <el-card>
      <div slot="header" class="clearfix">
        <span>条件搜索</span>
        <div class="base-el-float-right">
          <el-button-group>
            <el-button type="primary" icon="el-icon-refresh" @click="resetForm">重置</el-button>
            <el-button type="primary" icon="el-icon-search" @click="submitForm">搜索</el-button>
          </el-button-group>
        </div>
      </div>
      <el-form ref="ruleForm" :inline="true" :model="formInline">
        <el-form-item label="产品标题:">
          <el-input v-model="formInline.title" placeholder="请输入产品标题" />
        </el-form-item>
        <el-form-item label="主分类:">
          <el-select v-model="formInline.mainCategoryId">
            <el-option v-for="item of categoryData" :key="item._id" :label="item.name" :value="item._id" />
          </el-select>
        </el-form-item>
        <el-form-item label="子分类:">
          <el-select v-model="formInline.subCategoryId">
            <el-option
              v-for="item of formInline.mainCategoryId ? categoryData.find(v => v._id === formInline.mainCategoryId).subCategory : []"
              :key="item._id"
              :label="item.name"
              :value="item._id"
            />
          </el-select>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 产品列表 -->
    <el-card class="base-el-card-bottom">
      <div slot="header" class="clearfix">
        <span>产品列表</span>
        <el-button class="base-el-float-right" type="primary" icon="el-icon-plus" @click="handleEdit(false)">新增</el-button>
      </div>
      <PaginationTable
        :table-data="tableData"
        :total="total"
        :page-size="pageSize"
        :current-page="currentPage"
        @handleChange="handleTableSizeChange"
      >
        <el-table-column label="序号" type="index" width="50" />
        <el-table-column label="产品图片" width="100">
          <template slot-scope="scope">
            <el-image :src="scope.row.images[0]" :preview-src-list="scope.row.images" />
          </template>
        </el-table-column>
        <el-table-column label="归属" width="120">
          <template slot-scope="scope">
            <p>省份：<b>{{ area.areaName }}</b></p>
            <p>主分类：<b>{{ categoryFilter(scope.row.mainCategoryId) }}</b></p>
            <p>子分类：<b>{{ categoryFilter(scope.row.mainCategoryId, scope.row.subCategoryId) }}</b></p>
          </template>
        </el-table-column>
        <el-table-column label="产品信息" width="150">
          <template slot-scope="scope">
            <p>评分：<b>{{ scope.row.score }}</b>分</p>
            <p>标题：<b>{{ scope.row.title }}</b></p>
            <p>简介：{{ scope.row.description }}</p>
          </template>
        </el-table-column>
        <el-table-column label="产品标签">
          <template slot-scope="scope">
            <el-tag v-for="item of scope.row.tags" :key="item" type="primary">{{ item }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="产品规格" width="200">
          <template slot-scope="scope">
            <p v-for="item of scope.row.specs" :key="item.title">{{ item.title }}：{{ item.description }}</p>
          </template>
        </el-table-column>
        <el-table-column label="sku列表" width="250">
          <template slot-scope="scope">
            <p v-for="item of scope.row.skus" :key="item.id">
              {{ item.title }}：<span style="color: red">￥{{ item.price / 100 }}</span>
              <span v-if="item.originalPrice">（原价：￥{{ item.originalPrice / 100 }}）</span></p>
          </template>
        </el-table-column>
        <el-table-column label="排序" prop="sort" width="60" />
        <el-table-column label="是否上架" width="100">
          <template slot-scope="scope">
            <el-tag :type="scope.row.isEnable ? 'success' : 'danger'">{{ scope.row.isEnable ? '是' : '否' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间">
          <template slot-scope="scope">
            <span>{{ scope.row.createTime | timeFormatFilter }}</span>
          </template>
        </el-table-column>

        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-link type="primary" @click="handleEdit(scope.row)">编辑</el-link><br>
            <el-link :type="scope.row.isEnable ? 'danger' : 'primary'" @click="handleEnableChange(scope.row)">{{ scope.row.isEnable ? '下架' : '上架' }}</el-link>
          </template>
        </el-table-column>
      </PaginationTable>

      <el-dialog :title="(dataForm._id ? '编辑' : '新增') + '产品'" :show-close="false" :visible="dialogVisible">
        <el-form ref="dataForm" :model="dataForm" :rules="rules" label-width="100px">
          <el-form-item label="产品图片：" prop="images">
            <batch-upload v-model="dataForm.images" :limit="10" :size="10" />
          </el-form-item>
          <el-form-item label="标题：" prop="title">
            <el-input v-model="dataForm.title" placeholder="请输入产品标题" />
          </el-form-item>
          <el-form-item label="描述：" prop="description">
            <el-input v-model="dataForm.description" type="textarea" placeholder="请输入产品描述" />
          </el-form-item>
          <el-form-item label="主分类：" prop="mainCategoryId">
            <el-select v-model="dataForm.mainCategoryId" placeholder="请选择主分类">
              <el-option
                v-for="item in categoryData"
                :key="item._id"
                :label="item.name"
                :value="item._id"
              />
            </el-select>
          </el-form-item>
          <el-form-item v-if="dataForm.mainCategoryId" label="子分类：" prop="subCategoryId">
            <el-select v-model="dataForm.subCategoryId" placeholder="请选择子分类">
              <el-option
                v-for="item in categoryData.find(v => v._id === dataForm.mainCategoryId).subCategory"
                :key="item._id"
                :label="item.name"
                :value="item._id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="sku：" prop="skus">
            <el-form ref="skuForm" :model="skuForm" :inline="true">
              <el-form-item label="sku标题" prop="title" required>
                <el-input v-model="skuForm.title" size="small" placeholder="例：一包(200g)" />
              </el-form-item>
              <el-form-item label="原价" prop="originalPrice">
                <el-input-number v-model="skuForm.originalPrice" :step="0.1" :precision="2" size="small" placeholder="单位：元" />
              </el-form-item>
              <el-form-item label="现价" prop="price" required>
                <el-input-number v-model="skuForm.price" :step="0.1" :precision="2" size="small" placeholder="单位：元" />
              </el-form-item>
              <el-button type="primary" size="small" @click="handleSkuAdd">添加</el-button>
            </el-form>
            <el-table :data="dataForm.skus">
              <el-table-column label="标题" prop="title" />
              <el-table-column label="原价">
                <template slot-scope="scope">
                  <span v-if="!scope.row.originalPrice">暂无</span>
                  <span v-else>￥{{ scope.row.originalPrice / 100 }}</span>
                </template>
              </el-table-column>
              <el-table-column label="现价">
                <template slot-scope="scope">
                  <span style="color: red">￥{{ scope.row.price / 100 }}</span>
                </template>
              </el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-link type="danger" @click="handleSkuDelete(scope.row, scope.$index)">删除</el-link>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
          <el-form-item label="规格说明：" prop="specs">
            <el-form ref="specForm" :model="specForm" :inline="true">
              <el-form-item label="标题" prop="title" required>
                <el-input v-model="specForm.title" size="small" placeholder="例：规格" />
              </el-form-item>
              <el-form-item label="说明" prop="description" required>
                <el-input v-model="specForm.description" size="small" placeholder="例：2.5kg*4包" />
              </el-form-item>
              <el-button type="primary" size="small" @click="handleSpecAdd">添加</el-button>
            </el-form>
            <el-table :data="dataForm.specs">
              <el-table-column label="标题" prop="title" />
              <el-table-column label="说明" prop="description" />
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-link type="danger" @click="handleSpecDelete(scope.row, scope.$index)">删除</el-link>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
          <el-form-item label="评分：" prop="score">
            <el-input v-model="dataForm.score" class="short-input" placeholder="例：5.00">
              <template slot="append">分</template>
            </el-input>
          </el-form-item>
          <el-form-item label="标签：" prop="tags">
            <el-tag v-for="tag in dataForm.tags" :key="tag" class="el-tag" closable :disable-transitions="false" @close="handleTagRemove(tag)">{{ tag }}</el-tag>
            <el-input
              v-if="tagInputVisible"
              ref="saveTagInput"
              v-model="tagValue"
              class="input-new-tag"
              size="small"
              @keyup.enter.native="handleInputConfirm"
              @blur="handleInputConfirm"
            />
            <el-button v-else class="button-new-tag" size="small" @click="showTagInput">+ 新标签</el-button>
          </el-form-item>
          <el-form-item label="排序：">
            <el-input-number v-model="dataForm.sort" :min="1" :step="1" />
          </el-form-item>
          <el-form-item label="是否上架：">
            <el-switch v-model="dataForm.isEnable" />
          </el-form-item>
        </el-form>
        <span slot="footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="doEdit">确认</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>
<script>
import PaginationTable from '@/components/PaginationTable'
import BatchUpload from '@/components/BatchUpload'
import { queryByCondition, updateById, insertRecord } from '@/api/commoncrud'
import { categoryList } from '@/api/need'
import { getRandomUuid } from '@/utils/common'
const defaultFormInline = {
  title: '',
  mainCategoryId: '',
  subCategoryId: ''
}
export default {
  name: 'Product',
  components: { PaginationTable, BatchUpload },
  data() {
    return {
      area: {},

      categoryData: [],
      tableData: [],
      total: 0,
      pageSize: 10,
      currentPage: 1,

      formInline: {
        ...defaultFormInline
      },

      tagInputVisible: false,
      tagValue: '',
      skuForm: {},
      specForm: {},
      dataForm: {
        mainCategoryId: '',
        subCategoryId: '',
        images: [],
        score: '',
        title: '',
        description: '',
        tags: [],
        skus: [],
        specs: [],
        isEnable: false,
        sort: 1
      },
      rules: {
        mainCategoryId: [{ required: true, trigger: 'blur', message: '请选择主分类' }],
        subCategoryId: [{ required: true, trigger: 'blur', message: '请选择子分类' }],
        images: [{ type: 'array', required: true, trigger: 'change', message: '请最少上传一张照片' }],
        title: [{ required: true, trigger: 'blur', message: '请填写产品标题' }],
        description: [{ required: true, trigger: 'blur', message: '请填写产品描述' }],
        skus: [{ type: 'array', required: true, trigger: 'change', message: '请最少设置一个sku' }]
      },

      dialogVisible: false
    }
  },
  watch: {
    'dataForm.mainCategoryId'() {
      this.dataForm.subCategoryId = ''
    }
  },
  async created() {
    this.area = JSON.parse(window.localStorage.getItem('defaultArea'))

    await this.fetchCategoryData()
    await this.fetchData()
  },
  methods: {
    async fetchData() {
      const query = { areaId: this.area._id, sort: { createTime: -1 }}
      Object.keys(this.formInline).forEach(key => {
        if (this.formInline[key]) { query[key] = this.formInline[key] }
      })
      if (query.title) query.title = { $regex: query.title }
      const res = await queryByCondition('product', (this.currentPage - 1) * this.pageSize, this.pageSize, query)
      this.tableData = res.data.documentList
      this.total = res.data.documentCount
    },
    async fetchCategoryData() {
      const res = await categoryList(this.area._id)
      this.categoryData = res.data
    },
    handleEdit(data) {
      if (data) {
        this.dataForm = { ...data }
      }
      this.dialogVisible = true
    },
    handleClose() {
      this.dataForm = {
        mainCategoryId: '',
        subCategoryId: '',
        images: [],
        score: '',
        title: '',
        description: '',
        tags: [],
        skus: [],
        specs: [],
        isEnable: false,
        sort: 1
      }
      this.dialogVisible = false
    },
    async doEdit() {
      this.$refs['dataForm'].validate(async validate => {
        if (validate) {
          const data = this.dataForm
          const modelId = data._id
          if (modelId) {
            delete data._id
            await updateById('product', modelId, data)
          } else {
            data.areaId = this.area._id
            await insertRecord('product', data)
          }
          this.handleClose()
          this.$message.success('操作成功!')
          await this.fetchData()
        }
      })
    },

    async handleEnableChange(data) {
      this.$alert(`确认${data.isEnable ? '下架' : '上架'}?`, '消息提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        showCancelButton: true,
        callback: async action => {
          if (action === 'confirm') {
            await updateById('product', data._id, { isEnable: !data.isEnable })
            this.$message.success(`${data.isEnable ? '下架' : '上架'}成功!`)
            await this.fetchData()
          }
        }
      })
    },

    // 分类过滤器
    categoryFilter(mainCategoryId, subCategoryId) {
      if (!mainCategoryId) return ''
      const mainCategory = this.categoryData.find(v => v._id === mainCategoryId)
      if (subCategoryId) {
        const subCategory = mainCategory.subCategory.find(v => v._id === subCategoryId)
        return subCategory.name
      }
      return mainCategory.name
    },

    // 标签
    handleTagRemove(tag) {
      this.dataForm.tags.splice(this.dataForm.tags.indexOf(tag), 1)
    },
    showTagInput() {
      this.tagInputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    handleInputConfirm() {
      const tagValue = this.tagValue
      if (tagValue) {
        this.dataForm.tags.push(tagValue)
      }
      this.tagInputVisible = false
      this.tagValue = ''
    },
    // sku
    handleSkuAdd() {
      this.$refs.skuForm.validate(validate => {
        if (validate) {
          const id = getRandomUuid()
          this.dataForm.skus.push({
            id,
            title: this.skuForm.title,
            originalPrice: this.skuForm.originalPrice ? this.skuForm.originalPrice * 100 : 0,
            price: this.skuForm.price * 100 })
          this.$message.success('添加成功!')
          this.$refs.skuForm.resetFields()
        }
      })
    },
    handleSkuDelete(sku, index) {
      this.$alert(`确认删除${sku.title}?`, '消息提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        showCancelButton: true,
        callback: action => {
          if (action === 'confirm') {
            this.dataForm.skus.splice(index, 1)
          }
        }
      })
    },

    // spec
    handleSpecAdd() {
      this.$refs.specForm.validate(validate => {
        if (validate) {
          this.dataForm.specs.push({
            title: this.specForm.title,
            description: this.specForm.description })
          this.$message.success('添加成功!')
          this.$refs.specForm.resetFields()
        }
      })
    },
    handleSpecDelete(spec, index) {
      this.$alert(`确认删除${spec.title}?`, '消息提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        showCancelButton: true,
        callback: action => {
          if (action === 'confirm') {
            this.dataForm.specs.splice(index, 1)
          }
        }
      })
    },

    // 表格数据
    async resetForm() {
      this.formInline = {
        ...defaultFormInline
      }
      this.currentPage = 1
      await this.fetchData()
    },
    async handleTableSizeChange({ currentPage, pageSize }) {
      this.pageSize = pageSize
      this.currentPage = currentPage
      await this.fetchData()
    },
    async submitForm() {
      this.currentPage = 1
      await this.fetchData()
    }
  }
}
</script>

<style scoped>
.short-input{
  width: 200px;
}
.el-tag {
  margin-right: 10px;
}
.button-new-tag {
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  vertical-align: bottom;
}
</style>
